import * as React from 'react';
import {Action} from 'redux';

import {IView} from '../types/IView';
import {ActionType} from './ActionType';
import {IWidget} from '../panes/widget/IWidget';

export interface CustomWidgetsState extends Array<IWidget> {
  [index: number]: IWidget;
}

interface CustomWidget {
  name: string;
  view: IView;
}

export interface CustomWidgetsAction extends Action {
  type: ActionType;
  widgets?: CustomWidget[];
}

function customWidgetsReducer(state: CustomWidgetsState = [], action: CustomWidgetsAction): CustomWidgetsState {
  switch (action.type) {
    case ActionType.LOADED_WIDGETS:
      return _addCustomWidgets(state, action.widgets);

    default:
      return state;
  }
}

function _addCustomWidgets(state: CustomWidgetsState, widgets: CustomWidget[]): CustomWidgetsState {
  if (!_isCustomWidgetChanged(state, widgets)) {
    return state;
  }

  const customWidgets: IWidget[] = [];
  widgets.forEach(view => {
    customWidgets.push({
      name: view.name,
      display: view.name,
      viewType: view.name,
      icon: () => {
        return (<span className="fa fa-object-group"/>);
      }
    });
  });

  return customWidgets;
}

function _isCustomWidgetChanged(state: CustomWidgetsState, widgets: CustomWidget[]): boolean {
  if (state.length !== widgets.length) {
    return true;
  }

  return widgets.some((widget: CustomWidget, index: number) => {
    // 如果新的组件和之前的, 对应的名称不一样了, 那么就当做是改变了
    return widget.name !== state[index].name;
  });
}

export default customWidgetsReducer;
